package com.nebula.salary.portal.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nebula.salary.common.utils.MD5Util;
import com.nebula.salary.common.utils.SecurityUtil;
import com.nebula.salary.model.dto.AnswerDto;
import com.nebula.salary.model.pojo.Answer;
import com.nebula.salary.portal.mapper.AnswerMapper;
import com.nebula.salary.portal.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户密保问题答案表 服务实现类
 * </p>
 *
 * @author codex
 * @since 2022-01-24
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    
    /**
     * 更新安全问题
     *
     * @param answerDto 安全问题答案
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAnswer(AnswerDto answerDto) {
        
        List<Answer> list = Lists.newArrayList();
        Answer answer = new Answer();
        answer.setUserId(SecurityUtil.getUserId());
        answer.setAnswer(MD5Util.MD5EncodeUtf8(answerDto.getAnswer1()));
        answer.setQuestionId(answerDto.getQuestion1());
        list.add(answer);
    
        answer = new Answer();
        answer.setUserId(SecurityUtil.getUserId());
        answer.setAnswer(MD5Util.MD5EncodeUtf8(answerDto.getAnswer2()));
        answer.setQuestionId(answerDto.getQuestion2());
        list.add(answer);
    
        answer = new Answer();
        answer.setUserId(SecurityUtil.getUserId());
        answer.setAnswer(MD5Util.MD5EncodeUtf8(answerDto.getAnswer3()));
        answer.setQuestionId(answerDto.getQuestion3());
        list.add(answer);
        
        // 删除安全问题
        HashMap<String, Object> map = Maps.newHashMap();
        map.put(Answer.USER_ID, SecurityUtil.getUserId());
        baseMapper.deleteByMap(map);
        
        return this.saveBatch(list);
    }
}
